﻿using Huirui.Cavan.Domain.MainBoundedContext.SearchModule;
using Huirui.Cavan.Domain.MainBoundedContext.SystemModule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Huirui.Cavan.Domain.Seedwork;
using Spring.Context.Support;
using Huirui.Cavan.Core.Extension;

namespace Huirui.Cavan.Application.MainBoundedContext.SystemModule
{
    public class AccountAppService : BaseAppService<Account, string, AccountSearch, IAccountRepository>, IAccountAppService
    {
        #region IAccountAppService Members

        public override BoolGenericResult<Account> AddOrUpdate(Account entity)
        {
            Init();
            BoolGenericResult<Account> result = new BoolGenericResult<Account>();
            if (entity.IsNull())
            {
                throw new ArgumentNullException("");
            }
            Employee employee = this.EmployeeAppService.GetBySearch(SearchFactory.CreateEmployeeSearch(SecurityAppService.UserAccount.Id)).FirstOrDefault();
            Administrator admin = new Administrator(employee);

            Account oldAccount = null;
            if (entity.Id.IsNotEmpty())
            {
                oldAccount = this.Repository.Get(entity.Id);
            }
            if (oldAccount.IsNull())
            {
                IIDGenerateAppService idGenerateAppService = this.SpringContext.GetObject(SystemModuleConst.IDGENERATEAPPSERVICE, new object[] { employee.Corporation }) as IIDGenerateAppService;
                if (entity.Id.IsEmpty())
                {
                    entity.Id = idGenerateAppService.GenerateID(SystemIdentifier.BaseCodeRuleType.Account);
                }
                else
                {
                    idGenerateAppService.GenerateID(SystemIdentifier.BaseCodeRuleType.Account);
                }
                result = admin.AddAccount(entity.Id, entity.Name, entity.Currency, entity.Type, entity.Status);
                if (result.IsSuccess)
                    return base.Add(result.Object);
            }
            else
            {
                result = admin.UpdateAccount(oldAccount, entity.Name, entity.Currency,entity.InitialAmount, entity.Type,entity.Status);
                if (result.IsSuccess)
                    return base.Update(result.Object);
            }
            return result;
        }

        #endregion
    }
}
